package com.csdj.springcloudt309.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class LoginFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String uid = exchange.getRequest().getHeaders().getFirst("uid");
        if(StringUtils.hasText(uid)){
            String token = exchange.getRequest().getHeaders().getFirst("token");
            if(StringUtils.hasText(token)){
                if("1".equals(uid) && "token".equals(token)){
                    return chain.filter(exchange);
                }
            }
        }
        ServerHttpResponse response = exchange.getResponse();
        DataBufferFactory dataBufferFactory = response.bufferFactory();
        DataBuffer data = dataBufferFactory.wrap("no login".getBytes());
        return response.writeWith(Mono.just(data));


    }

    @Override
    public int getOrder() {
        return -100;
    }
}
